package com.lagou.stage1.module4.task3;

import java.util.concurrent.locks.ReentrantLock;


public class BuyTicketThread extends Thread {
    //定义静态变量i,控制火车票号
    private static int i = 100;
    //定义lock引用
    private ReentrantLock lock = new ReentrantLock();



    //getter setter方法
    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
    }
    //重写run方法
    @Override
    public void run() {
        //获取线程名称
        System.out.println("线程" + Thread.currentThread().getName() + "已经启动.");
        //加锁
        synchronized (BuyTicketThread.class) {
            while (true) {

                //调用之前检测i是否<=0,如果是退出当前循环
                if (i <= 0) {
                    break;
                }

                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //打印被买走的火车票,并做i--操作
                System.out.println("编号为: " + i-- + "的火车票已经被线程: " + Thread.currentThread().getName() + "购买.");

            }
        }
    }



    public static void main(String[] args) {
        //定义引用来创建线程
        BuyTicketThread btt = new BuyTicketThread();
        Thread btt1 = new Thread(btt);
        Thread btt2 = new Thread(btt);
        Thread btt3 = new Thread(btt);
        btt1.start();
        btt2.start();
        btt3.start();
        //使用join做阻塞
        try {
            btt1.join();
            btt2.join();
            btt3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("主线程开始等待....");
    }
}
